the ultrasonic sensor sensor (HC-SR04) has 4 pins, the vcc (in-going current) pin, the trig (trigger) pin, the echo pin and the gnd (ground) pin.
The trig pin is needed to send a signal out, as pointed out in this link: source. The echo pin is needed to send and receive the signal and calculate the time taken.
as seen in the image (credits to abdularbi17 @their arduino website), the HC-SR04 can detect between 2cm to 450cm, needs to be elevated at 15 degrees to gauge the right distance, and needs a minimum of 0.3cm to pick up the echo it sent out.
this image is also from abdularbi17. The left side will always be the one to send out a signal, whereas the right side would receive said signal. In the image, one can notice that there are 2 waves. that means that one wave is before hitting an object (i.e. sending signal) whereas the other wave is after the object is hit (i.e. returning signal). This means that the signal travels twice the actual distance.
the code below shows a few important bits like "Clear the trigpin condition", "pulseIn()" and "distance = duration * 0.034 /2".
You will need to clear the trigpin condition to ensure it doesnt send a random signal out beforehand.
pulseIn() reads the changes in a digital signal. For example, if the given value is HIGH, then pulseIn() waits for the signal to go HIGH, and record the time taken before the signal goes to LOW. it can only work between 10ms to 3min, so that means that no value will be provided if it exceeds said timing. There is bound to be some level of error since the timing was done via observation of the device.
The distance calculation is based off the mathematics and science behind echolocation, since the speed of sound in air is ~340m/s. As our duration is in miliseconds, we converted the speed of sound in air to mm/s, hence the 0.034. The distance is divided by 2 since the sound travels 2 times the distance, one to hit the object and one to return to the sensor.
Here's the original code (with download link at image below!)